package com.apexsoft.front.common.db.mysql;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;


public class DaoSupportMapper implements RowMapper<Object> {

	Class<?> clazz;

	public DaoSupportMapper(Class<? extends ReflectObject> type) {
		super();
		clazz = type;
	}

	public ReflectObject mapRow(ResultSet rs, int row) throws SQLException {
		ReflectObject o;
		try {
			o = getObjectInstance();
		} catch (InstantiationException e) {
			throw new SQLException("can't instance object:" + clazz.getName(), e);
		} catch (IllegalAccessException e) {
			throw new SQLException("can't instance object:" + clazz.getName(), e);
		}
		MysqlResultSetParser.parse(rs, row, o);
		return o;

	}

	private ReflectObject getObjectInstance() throws InstantiationException, IllegalAccessException {
		return (ReflectObject) clazz.newInstance();
	}

	/**
	 * 解析列名，表字段名-变量名
	 * 表字段格式ABC_XYZ
	 * 变量名，驼峰式 abcXyz
	 * @param columnName 列字段名
	 * @return
	 */
	public static String parseFieldName(String columnName) {
		if (columnName == null)
			return null;
		
		String[] ss = columnName.toLowerCase().split("_");
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < ss.length; i++) {
			if(i==0){
				sb.append(ss[i]);
			}else{
				sb.append(ss[i].substring(0, 1).toUpperCase() + ss[i].substring(1));
			}
			
		}
		return sb.toString();
	}
	
	/**
	 * 解析多个列名，表字段名-变量名
	 * @param columnNames 列字段列表
	 * @return
	 */
	public static String[] parseFieldNames(String[] columnNames) {
		if (columnNames == null)
			return null;
		
		String[] newColumnNames = new String[columnNames.length];
		for (int i = 0; i < columnNames.length; i++) {
			newColumnNames[i] = parseFieldName(columnNames[i]);
		}
		return newColumnNames;
	}
}
